#include <stdio.h>
#include <stdint.h>
#include <string.h>

#include "sysconfig.h"
#include "sysdeps.h"
#include "custom.h"

#include "text_scope.h"

#include "uade.h"

static char* PaulaEventStr[] = {"Vol", "Per", "Dat", "Len", "LCL", "LCH"};

static char txt_file[1000];
static FILE* file = NULL;

static void print_tab(int v)
{
    int i;
    char spaces[20];

    memset(spaces, ' ', sizeof spaces);

    for (i = 0; i < v; i++)
        fwrite(spaces, sizeof spaces, 1, stdout);
}

static void setup_txt_file()
{
    #define EVAL_MAX_LEN (300)

    int nLen;

    char in[1000];
    strcpy(in, song.modulename);

    // Get string length !!!
    nLen = strlen (in);

    if ((nLen > 0) && (nLen < EVAL_MAX_LEN)) 
    {
        while (nLen) 
        {
            // Check for extension character !!!
            if (in[nLen] == '.') 
            {
                in[nLen] = '\0';
                break;
            }

            nLen --;
        }

        // Create output file name and with new extension
        sprintf (txt_file, "%s.txt", in);
    }
}

static void open_file()
{
    if (file != NULL)
        return;

    setup_txt_file();
    file = fopen(txt_file, "w+");
    fprintf(file, "cycles;channel(0-3);value(-8064-8001)\n");
}

void text_scope(unsigned long cycles, int voice, enum PaulaEventType e,
    int value)
{
    //unsigned int sec = cycles / SOUNDTICKS;
    //unsigned int usec = ((uint64_t) (cycles % SOUNDTICKS) * 1000000) / SOUNDTICKS;
    
    //printf("%6u:%.6u ", sec & 0x1ffff, usec);
    //print_tab(voice);

    //open_file();
    //fprintf(file, "%s;%ul;%d;%d\n", PaulaEventStr[e], cycles, value, voice);
}

void text_scope_2(int channel, int value, int cycles)
{
    open_file();

    fprintf(file, "%d;%d;%d\n", cycles, channel, value);
}